﻿#include "taskmanager.h"
#include "ui_taskmanager.h"


//http://172.16.21.101/workplace-manage
taskManager::taskManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::taskManager)
{
    ui->setupUi(this);
    qRegisterMetaType<ESS_Request >("ESS_Request");
    qRegisterMetaType<QMap<int,SAPExcelInfo>>("QMap<int,SAPExcelInfo>");


    taskManagerInit();

    StTimer = new QTimer(this);
    CameraStationUpdate = new QTimer(this);
    connect(StTimer,&QTimer::timeout,this,&taskManager::ON_taskManagerTimer); //任务管理槽函数
    StTimer->start(600);

    connect(CameraStationUpdate,&QTimer::timeout,this,&taskManager::ON_CameraStationUpdate);    //通过摄像头查询库位状态槽函数
//    CameraStationUpdate->start(12000); //丢弃 不使用这里获取相机状态 通过cameraControl 获取 定时12s从摄像头获取库位状态

    /**
     * 赖俊龙
     * 隐藏历史任务界面无用项
     */
    // 隐藏 widget 组件
    ui->widget->hide();

}

taskManager::~taskManager()
{
    delete ui;
}

void taskManager::taskManagerInit()
{

    actionIdMap.insert("创建ESS任务_IN","action4");     //出库
    actionIdMap.insert("创建ESS任务_OUT","action2");    //回库-->入库
    actionIdMap.insert("取消ESS任务","action5");        //任务取消请求
    actionIdMap.insert("STATION-01_入场","action6");
    actionIdMap.insert("STATION-03_离场","action7");
    actionIdMap.insert("STATION-04_离场","action7");

    currentTypeMap.insert("装机位->老化房","IN");
    currentTypeMap.insert("老化房->下机位","OUT");
    currentTypeMap.insert("老化房->装机位","Empty");
    currentTypeMap.insert("下机位->老化房","Empty");
    currentTypeMap.insert("下机位->装机位","Empty");

    wrexcelprocessItiem=new wrexcelprocess;
    wrexcelprocessItiem->hide();

    //IconHelper::Instance()->setIcon(ui->last_Button, 0xf0ec, 15);
    ui->Selete_DateEdit->setDateTime(QDateTime::fromString(QDateTime::currentDateTime().toString("yyyy-MM-dd")+" 00:00:00" ,"yyyy-MM-dd hh:mm:ss"));
    ui->Selete_DateEdit_2->setDateTime(QDateTime::fromString(QDateTime::currentDateTime().toString("yyyy-MM-dd")+" 23:59:00" ,"yyyy-MM-dd hh:mm:ss"));

    table_single::GetInstance()->TableWidgetInit(ui->tableWidget,12,"QHeaderView::section{background-color:rgb(211, 215, 212);font:12pt '宋体';color: black;};",30,30);
    connect(ui->tableWidget,&QTableWidget::cellClicked,this,&taskManager::SlotsetCurrentItem);

    ui->stackedWidget->setCurrentIndex(0);
    ui->stackedWidget->widget(0)->layout()->setContentsMargins(0,0,0,0);
    ui->stackedWidget_3->setCurrentIndex(0);
    ui->stackedWidget_3->widget(0)->layout()->setContentsMargins(0,0,0,0);

}


void taskManager::ON_taskManagerTimer()
{
    TableWidgetcount++;
    if(countbool){
        countbool=false;

        if(ServerInitItem.UserInfoList.isEmpty()){
            /************** 基础信息赋值 *******************/
            allServerInit ALLServerInitItem=queryServer::getInstance()->getCurrentServerInitItem();
            ServerInitItem=ALLServerInitItem.ServerInitItem;
            CurrentServerItem=ALLServerInitItem.CurrentServerItem;
        }

        if(TableWidgetcount%3==0){
           if(!currentlabelMap.isEmpty()){
               ReplyMsg ReplyMsgI=sapMsgInterface::getInstance()->GetMsgRecv_Msg(currentlabelMap.firstKey());
               if(ReplyMsgI.keyId!=""){
                   ui->lineEdit_table->setText("指令执行反馈-->Msg:"+ReplyMsgI.errorMsg+"   更新时间:"+QDateTime::currentDateTime().toString());
                   currentlabelMap.remove(currentlabelMap.firstKey());
               }
           }
       }
       countbool=true;
    }

    if(TableWidgetcount>10000){TableWidgetcount=0;}

}

//摄像头定时获取全部库位状态槽函数
void taskManager::ON_CameraStationUpdate()
{

        ESS_Request ESS_RequestI;
        ESS_RequestI.actionId="action6";
        ESS_RequestI.pathId = 1016;
        ESS_Single::GetInstance()->setESS_RequestI(seletSAPExcelInfoI,ESS_RequestI,ESS_RequestI.actionId,0,0);

        qDebug()<<" 发送的pathId:"<<ESS_RequestI.pathId<<"发送的actionId:"<<ESS_RequestI.actionId;
}

void taskManager::SlotsetCurrentItem(int row, int column)
{
    SAPExcelInfo SAPExcelInfoI;
    seletSAPExcelInfoI=SAPExcelInfoI;

    /**
     * 赖俊龙
     * 修改任务历史表格序列号位置
     */
    int SAPTaskIndex=ui->tableWidget->item(row,9)->text().trimmed().toInt();

    QMap<int, SAPExcelInfo>::iterator iter= seletSAPExcelInfoTask.begin();
    while (iter !=seletSAPExcelInfoTask.end()) {
        if(iter.value().SAPTaskIndex==SAPTaskIndex){
            if(iter.value().checked==0){//选中
                iter.value().checked=1;
                seletSAPExcelInfoI=iter.value();
            }else {
                iter.value().checked=0;
            }
        }else{
            iter.value().checked=0;
        }
        iter++;
    }
    tableWidget_Show();//tableWidget 更新显示

    ui->lineEdit_table->setText("-----> taskType:"+seletSAPExcelInfoI.taskType+"  taskId:"+seletSAPExcelInfoI.taskId
                                +"  taskId_ess:"+seletSAPExcelInfoI.taskId_ess+"  taskId_agv:"+seletSAPExcelInfoI.taskId_agv+
                                "   taskStatus:"+QString::number(seletSAPExcelInfoI.taskStatus)+seletSAPExcelInfoI.taskStatusDesc);

}

void taskManager::ON_Translate()
{
    qApp->installTranslator(&ESS_Single::GetInstance()->trans);
    ui->retranslateUi(this);

    // 判断表格是否有数据
    if (ui->tableWidget->rowCount() > 0) {
        //查询按钮槽函数
        on_Qury_Button_clicked();
    }
}

void taskManager::tableWidget_Show()
{
    //解决显示卡顿问题:  https://blog.csdn.net/u014746838/article/details/102642083
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    QStringList comBoxlist;
    QList<RW_Excel> ExcelList=TableWidget();
    table_single::GetInstance()->UP_TableWidget(ui->tableWidget,ExcelList,comBoxlist,0);
    if(ExcelList.isEmpty()){
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//列宽根据表格大小自适应
        return;
    }
    /**
     * 赖俊龙
     * 设置历史任务界面表格显示自适应
     */
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//列宽根据表格大小自适应
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(3,QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(6,QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(7,QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(9,QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(10,QHeaderView::ResizeToContents);

}

QList<RW_Excel> taskManager::TableWidget()
{
    QList<RW_Excel> ExcelList;
    QList<RW_Excel> ExcelList0;
    QList<RW_Excel> ExcelList1;
    QList<RW_Excel> ExcelList2;
    QList<RW_Excel> ExcelList3;

    foreach(SAPExcelInfo iter,seletSAPExcelInfoTask.values())
    {
        int incount=0;
        RW_Excel RW_ExcelItem;
        RW_ExcelItem.ExcelB=iter.taskType;                                                          // 任务类型
        RW_ExcelItem.ExcelC=iter.taskTypeDesc;                                                      // 任务类型描述
        RW_ExcelItem.ExcelD=iter.taskId;                                                            // 订单编码
        RW_ExcelItem.ExcelE=iter.load;                                                              // 起始库位
        RW_ExcelItem.ExcelF=iter.unload;                                                            // 目标库位
        RW_ExcelItem.ExcelG=iter.agvNum;                                                            // AGV编号
        RW_ExcelItem.ExcelH=iter.taskStatusDesc+"-"+QString::number(iter.taskStatus);               // 任务状态注释
        RW_ExcelItem.ExcelI=QString::number(iter.SAPTaskIndex);                                     // 序列编号
        RW_ExcelItem.ExcelJ=iter.creatTimer.toString("yyyy-MM-dd hh:mm:ss");                        // 任务开始时间
        RW_ExcelItem.ExcelK=iter.finishTimer.toString("yyyy-MM-dd hh:mm:ss");                       // 任务结束时间
        RW_ExcelItem.checked=iter.checked;

//        if(iter.taskStatus==taskTake_wait || iter.taskStatus==taskTake_wait2){
//            incount=1;
//            RW_ExcelItem.corlor=2;       // 0
//            ExcelList.append(RW_ExcelItem);
//        }
        if(incount==0){
            incount=1;
            RW_ExcelItem.corlor=0;       // 0
            ExcelList2.append(RW_ExcelItem);
        }if(incount==0 && iter.taskStatus>100){
            incount=1;
            RW_ExcelItem.corlor=2;       // 0
            ExcelList3.append(RW_ExcelItem);
        }

    }

    ExcelList=ExcelList0+ExcelList1+ExcelList2+ExcelList3;
    for (int i=0;i<ExcelList.size();i++) {
        ExcelList[i].ExcelA=QString::number(i+1);
    }
    ui->lineEdit_count->setText(tr("项数：")+QString::number(ExcelList.size()));
    return ExcelList;
}


void taskManager::on_Delete_Button_clicked()
{
    if(ui->checkBox_Edite->isChecked()){
        if(seletSAPExcelInfoI.SAPTaskIndex>0){
            emit sig_deleteSAPExcelInfoTask(seletSAPExcelInfoI);
        }else{
            ui->lineEdit_table->setText("存在正在执行的任务,无法执行删除");
        }
        on_Cancel_Button_clicked();
    }
}

void taskManager::on_Qury_Button_clicked()
{
    seletSAPExcelInfoTask.clear();
    this->setCursor(Qt::BusyCursor);//后台运行状态
    ui->Qury_Button->setEnabled(false);

    slecetSAP_Log slecetSAP_LogI;

    // 任务类型
    if(ui->taskTypeBox->currentIndex()!=0){
        if(ui->taskTypeBox->currentIndex() == 1){
            slecetSAP_LogI.taskType="ONE";

        }else if(ui->taskTypeBox->currentIndex() == 2){
            slecetSAP_LogI.taskType="TWO";

        }else if(ui->taskTypeBox->currentIndex() == 3){
            slecetSAP_LogI.taskType="THREE";

        }
    }

    // 任务状态
    if(ui->taskStatusBox->currentIndex() == 0){
        slecetSAP_LogI.taskStatus_s=0;
        slecetSAP_LogI.taskStatus_e=1000;
    }else if(ui->taskStatusBox->currentIndex() == 1){
         slecetSAP_LogI.taskStatus_s=0;
         slecetSAP_LogI.taskStatus_e=0;
    }else if(ui->taskStatusBox->currentIndex() == 2){
        slecetSAP_LogI.taskStatus_s=1;
        slecetSAP_LogI.taskStatus_e=99;
    }else if(ui->taskStatusBox->currentIndex() == 3){
        slecetSAP_LogI.taskStatus_s=100;
        slecetSAP_LogI.taskStatus_e=100;
    }else if(ui->taskStatusBox->currentIndex() == 4){
        slecetSAP_LogI.taskStatus_s=101;
        slecetSAP_LogI.taskStatus_e=101;
    }

    //读取工单条码标签
    int labelNoNumber=ui->LabelNolineEdit->document()->lineCount();
    for(int n=0;n<labelNoNumber;n++){
         QString labelNo=ui->LabelNolineEdit->toPlainText().section('\n',n-labelNoNumber,n-labelNoNumber,QString::SectionSkipEmpty); //取得每行（以换行符进行换行）
         if(!slecetSAP_LogI.labelNoMap.contains(labelNo) && labelNo!=""){
             slecetSAP_LogI.labelNoMap.insert(labelNo,labelNo);
         }
    }

    int CodeNumber=ui->GetorderId->document()->lineCount(); //读取TextEdit里的行数
    for(int n=0;n<CodeNumber;n++){
         QString material=ui->GetorderId->toPlainText().section('\n',n-CodeNumber,n-CodeNumber,QString::SectionSkipEmpty); //取得每行（以换行符进行换行）
         if(!slecetSAP_LogI.materialMap.contains(material) && material!=""){
             slecetSAP_LogI.materialMap.insert(material,material);
         }
    }

    slecetSAP_LogI.QDateTimeS=ui->Selete_DateEdit->dateTime();
    slecetSAP_LogI.QDateTimeE=ui->Selete_DateEdit_2->dateTime();
    seletSAPExcelInfoTask=queryServer::getInstance()->querySAPExcelInfoList(slecetSAP_LogI);

    tableWidget_Show();//tableWidget 更新显示

    ui->Qury_Button->setEnabled(true);
    this->setCursor(Qt::ArrowCursor);//正常状态
}

void taskManager::on_Cancel_Button_clicked()
{
    SAPExcelInfo SAPExcelInfoI;
    seletSAPExcelInfoI=SAPExcelInfoI;
    seletSAPExcelInfoTask.clear();
    tableWidget_Show();//tableWidget 更新显示

    //清空工单条码标签
    ui->LabelNolineEdit->clear();
}

void taskManager::on_AgvExecute_clicked()
{
    if(ui->taskType->currentIndex()==0){
        queryServer::getInstance()->SetMessagebox("请选择任务类型.");
        return;
    }

    if(queryServer::getInstance()->SetMessagebox("是否执行任务创建指令?")){
        if(ui->workStation_box->currentText().trimmed()!=""){
            ESS_Request ESS_RequestI;
            ESS_RequestI.actionId="WS01";
            if(ui->lineEdit_taskId_mes->text().trimmed()!=""){
                ESS_RequestI.taskId=ui->lineEdit_taskId_mes->text().trimmed();   //任务唯一编码;
            }else{
                ESS_RequestI.taskId="AGVTaskId"+QDateTime::currentDateTime().toString("mmsszzz");   //任务唯一编码;
            }

            QString taskType =ui->taskType->currentText().trimmed();                            //任务类型
            ESS_RequestI.taskType=currentTypeMap.value(taskType);
            if(taskType=="装机位->老化房"){
                ESS_RequestI.load=ServerInitItem.StationDesMap.value("装机站点1");          //装机站点
                ESS_RequestI.unload=ServerInitItem.StationDesMap.value(ui->workStation_box->currentText().trimmed());   //老化工位
            }if(taskType=="老化房->下机位"){
                ESS_RequestI.load=ServerInitItem.StationDesMap.value(ui->workStation_box->currentText().trimmed());   //老化工位
                ESS_RequestI.unload=ServerInitItem.StationDesMap.value("下机站点1");      //下机站点
            }if(taskType=="老化房->装机位"){
                ESS_RequestI.load=ServerInitItem.StationDesMap.value(ui->workStation_box->currentText().trimmed());   //老化工位
                ESS_RequestI.unload=ServerInitItem.StationDesMap.value("装机站点1");          //装机站点
            }if(taskType=="下机位->老化房"){
                ESS_RequestI.unload=ServerInitItem.StationDesMap.value("下机站点1");      //下机站点
                ESS_RequestI.workStation=ServerInitItem.StationDesMap.value(ui->workStation_box->currentText().trimmed());   //老化工位
            }if(taskType=="下机位->装机位"){
                ESS_RequestI.unload=ServerInitItem.StationDesMap.value("下机站点1");        //下机位
                ESS_RequestI.load=ServerInitItem.StationDesMap.value("装机站点1");          //装机站点
            }

            ESS_RequestI=ESS_Single::GetInstance()->setESS_RequestI(seletSAPExcelInfoI,ESS_RequestI,ESS_RequestI.actionId,0,0);

            qDebug()<<" 手动下达MES任务-->taskId:"<<ESS_RequestI.taskId
                   <<" load:"<<ESS_RequestI.load<<" workStation:"<<ESS_RequestI.workStation<<" unload"<<ESS_RequestI.unload;
            currentlabelMap.insert(ESS_RequestI.iKey,ESS_RequestI.workStation);

            on_Cancel_Button_clicked();
            ui->taskType->setCurrentIndex(0);
            ui->lineEdit_table->setText("new task-->taskId:"+ESS_RequestI.taskId+" "+ESS_RequestI.workStation+"  时间:"+QDateTime::currentDateTime().toString("hh:mm:ss"));
        }else{
            ui->lineEdit_table->setText("注释:老化工位名称: "+QDateTime::currentDateTime().toString());
        }
    }

}

void taskManager::on_AgvExecute_re_clicked()
{
    if(queryServer::getInstance()->SetMessagebox("是否重新执行当前运行任务?")){
        if(seletSAPExcelInfoI.SAPTaskIndex>0 && seletSAPExcelInfoI.taskStatus>=1){
            ESS_Request ESS_RequestI;
            ESS_RequestI.actionId="WS01";
            ESS_RequestI.taskId=seletSAPExcelInfoI.taskId;      //任务唯一编码;
            ESS_RequestI.taskType=seletSAPExcelInfoI.taskType;

            ESS_RequestI.load=seletSAPExcelInfoI.load;          //装机站点
            ESS_RequestI.workStation=seletSAPExcelInfoI.workStation;
            ESS_RequestI.unload=seletSAPExcelInfoI.unload;      //下机站点

            ESS_RequestI=ESS_Single::GetInstance()->setESS_RequestI(seletSAPExcelInfoI,ESS_RequestI,ESS_RequestI.actionId,0,0);
            qDebug()<<" 重新执行当前-->taskId:"<<ESS_RequestI.taskId
                   <<" load:"<<ESS_RequestI.load<<" workStation:"<<ESS_RequestI.workStation<<" unload"<<ESS_RequestI.unload;
            currentlabelMap.insert(ESS_RequestI.iKey,ESS_RequestI.workStation);

            on_Cancel_Button_clicked();
            ui->taskType->setCurrentIndex(0);
            ui->lineEdit_table->setText("new task-->taskId:"+ESS_RequestI.taskId+" "+ESS_RequestI.workStation+"  时间:"+QDateTime::currentDateTime().toString("hh:mm:ss"));
        }else{
            ui->lineEdit_table->setText("注释:请选择可以重新执行项 "+QDateTime::currentDateTime().toString());
        }
    }
}

void taskManager::on_loadPass_clicked()
{
    if(queryServer::getInstance()->SetMessagebox("是否执行装机站点1放行指令?")){
        if(seletSAPExcelInfoI.SAPTaskIndex>0){
            ESS_Request ESS_RequestI;
            ESS_RequestI.actionId="action3";
            ESS_RequestI.status=seletSAPExcelInfoI.taskStatus;
            ESS_RequestI.agvId=seletSAPExcelInfoI.agvNum.toInt();
            ESS_RequestI.taskId=seletSAPExcelInfoI.taskId_ess; //任务唯一编码;
            ESS_RequestI=ESS_Single::GetInstance()->setESS_RequestI(seletSAPExcelInfoI,ESS_RequestI,ESS_RequestI.actionId,0,0);

            qDebug()<<" 装机站点放行指令-->taskId:"<<ESS_RequestI.taskId
                   <<" load:"<<ESS_RequestI.load<<" workStation:"<<ESS_RequestI.workStation<<" unload"<<ESS_RequestI.unload;
            currentlabelMap.insert(ESS_RequestI.iKey,ESS_RequestI.workStation);
            on_Cancel_Button_clicked();
            ui->lineEdit_table->setText("装机站点1放行指令-->taskId:"+ESS_RequestI.taskId+" "+ESS_RequestI.workStation+"  时间:"+QDateTime::currentDateTime().toString("hh:mm:ss"));
        }else{
            ui->lineEdit_table->setText("注释:请选择放行项 "+QDateTime::currentDateTime().toString());
        }
    }

}

void taskManager::on_AgvExecute_2_clicked()
{
    QString taskId =ui->lineEdit_taskId->text().trimmed();
    QString taskType =ui->taskType->currentText().trimmed();
    if(taskId!=""){
        if(queryServer::getInstance()->SetMessagebox("是否设置MES任务完成?")){
            SAPExcelInfo SAPExcelInfoI;
            SAPExcelInfoI.taskId=taskId;                                        //订单编码唯一
            SAPExcelInfoI.taskType=currentTypeMap.value(taskType);              //任务类型
            SAPExcelInfoI.taskTypeDesc=taskType;
            SAPExcelInfoI.agvNum="0";                                           //配送小车编号
            SAPExcelInfoI.Priority=100;                                         //任务优先级
            SAPExcelInfoI.load=ServerInitItem.StationDesMap.value("装机站点1");            //装机站点
            SAPExcelInfoI.workStation=ServerInitItem.StationDesMap.value(ui->workStation_box->currentText().trimmed());    //老化工位
            SAPExcelInfoI.unload=ServerInitItem.StationDesMap.value("下机站点1");       //下机站点
            SAPExcelInfoI.taskStatus=103;
            SAPExcelInfoI.taskStatusDesc="设置MES任务完成";
            SAPExcelInfoI.creatTimer=QDateTime::currentDateTime();
            emit sig_SAPExcelInfo_new(SAPExcelInfoI);

            on_Cancel_Button_clicked();
            ui->taskType->setCurrentIndex(0);
        }
    }

    ui->lineEdit_taskId->setText("");

}

void taskManager::on_AgvExecute_3_clicked()
{
    if(!seletSAPExcelInfoTask.isEmpty()){
        wrexcelprocessItiem->on_EXCEL_SAPMes_clicked(seletSAPExcelInfoTask);
    }else{
        queryServer::getInstance()->SetMessagebox("当前导出数据为空");
    }
}
